// src/main/java/com/service/impl/OverallProgressServiceImpl.java
package com.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;

import com.dao.OverallProgressDao;
import com.entity.OverallProgressEntity;
import com.service.OverallProgressService;
import com.service.LessonService; // 注入 LessonService 来获取课时信息
import com.service.LearningProgressService; // 注入 LearningProgressService 来获取单个课时进度

import com.entity.LessonEntity;
import com.entity.LearningProgressEntity;

import java.util.List;
import java.util.Objects; // 用于 Objects.isNull() 检查
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.mapper.EntityWrapper;


@Service("overallProgressService")
public class OverallProgressServiceImpl extends ServiceImpl<OverallProgressDao, OverallProgressEntity> implements OverallProgressService {

    @Autowired
    private LessonService lessonService; // 注入 LessonService
    @Autowired
    private LearningProgressService learningProgressService; // 注入 LearningProgressService

    @Override
    public OverallProgressEntity getOverallProgressByUserIdAndCourseId(Long userId, Long courseId) {
        List<OverallProgressEntity> list = this.baseMapper.selectList(new EntityWrapper<OverallProgressEntity>()
                .eq("user_id", userId)
                .eq("course_id", courseId)
                .last("LIMIT 1") // 建议加上，在数据库层面限制只查一条
        );

        if (list != null && !list.isEmpty()) {
            return list.get(0); // 返回找到的第一条记录
        }
        return null;
    }

    @Override
    public void calculateAndSaveOverallProgress(Long userId, Long courseId) {
        // 1. 获取该课程下所有视频课时的总时长 (course_overall_length)
        int totalVideoDuration = 0;
        List<LessonEntity> videoLessons = lessonService.selectList(
                new EntityWrapper<LessonEntity>()
                        .eq("course_id", courseId)
                        .eq("lesson_type", "video") // 假设视频课的类型是 "video"
        );

        for (LessonEntity lesson : videoLessons) {
            if (lesson.getDurationSeconds() != null) {
                totalVideoDuration += lesson.getDurationSeconds();
            }
        }

        // 2. 获取用户在该课程下已观看的视频总时长 (user_overall_progress)
        int userWatchedDuration = 0;
        List<LearningProgressEntity> userProgresses = learningProgressService.selectList( // 获取用户所有学习进度
                new EntityWrapper<LearningProgressEntity>()
                        .eq("user_id", userId)
        );

        // 获取该课程下所有视频课时的 lesson_id 列表，以便过滤 userProgresses
        List<Long> videoLessonIdsInCourse = videoLessons.stream()
                .map(LessonEntity::getId)
                .collect(Collectors.toList());

        for (LearningProgressEntity progress : userProgresses) {
            // 确保是该课程下的视频课时的进度，并且有 progressSeconds 字段
            if (videoLessonIdsInCourse.contains(progress.getLessonId()) && progress.getProgressSeconds() != null) {
                userWatchedDuration += progress.getProgressSeconds();
            }
        }

        // 3. 计算 progress_percent
        Float progressPercent = 0f;
        if (totalVideoDuration > 0) {
            progressPercent = (float) userWatchedDuration / totalVideoDuration;
        }

        // 4. 保存或更新 overall_progress 记录
        OverallProgressEntity overallProgress = getOverallProgressByUserIdAndCourseId(userId, courseId);

        if (overallProgress == null) {
            // 不存在则创建新记录
            overallProgress = new OverallProgressEntity();
            overallProgress.setUserId(userId);
            overallProgress.setCourseId(courseId);
            overallProgress.setCourseOverallLength(totalVideoDuration);
            overallProgress.setUserOverallProgress(userWatchedDuration);
            overallProgress.setProgressPercent(progressPercent);
            this.insert(overallProgress);
        } else {
            // 存在则更新
            overallProgress.setCourseOverallLength(totalVideoDuration);
            overallProgress.setUserOverallProgress(userWatchedDuration);
            overallProgress.setProgressPercent(progressPercent);
            this.updateById(overallProgress);
        }
    }

    @Override
    public List<OverallProgressEntity> getUserAllOverallProgresses(Long userId) {
        // 调用 Mapper 中自定义的联表查询方法
        return this.baseMapper.selectOverallProgressWithCourseInfo(userId);
    }


}
